package cn.hairui.blog.controller.manage;

import cn.hairui.blog.constant.PubConstant;
import cn.hairui.blog.model.Link;
import cn.hairui.blog.model.User;
import cn.hairui.blog.service.LinkService;
import cn.hairui.blog.service.WebInfoService;
import cn.hairui.blog.util.CommUtil;
import com.alibaba.druid.support.json.JSONUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author lihairui
 * @version V1.0
 * @date: 2019/8/18 15:44
 */
@Controller
@RequestMapping(value = "/manage")
public class LinkManageController {
    @Autowired
    private LinkService linkService;
    @Autowired
    private WebInfoService webInfoService;
    @Value("${upload_path}")
    private String uploadPath;

    @Value("${virtual_upload_path}")
    private String virtualUploadPath;

    //列表页面
    @RequestMapping(value = "page/link/linkList")
    public String linkList() {
        return "manage/page/link/linkList";
    }

    //新增页面
    @RequestMapping(value = "page/link/linkAdd")
    public String linkAdd() {
        return "manage/page/link/linkAdd";
    }

    //列表数据
    @RequestMapping(value = "page/link/list")
    @ResponseBody
    public String list(HttpServletRequest request) {
        Map map = new HashMap<Object, Object>();
        int pageSize = 5;//默认每页显示5条记录
        int pageNum = 1;
        try {
            pageNum = Integer.parseInt(request.getParameter("page"));
            pageSize = Integer.parseInt(request.getParameter("limit"));
        } catch (Exception e) {
        }
        PageHelper.startPage(pageNum, pageSize);
        List<Map> linkList = linkService.list();

        PageInfo<Map> pageInfo = new PageInfo<Map>(linkList);
        map.put("data", linkList);
        map.put("code", 0);
        map.put("count", pageInfo.getTotal());
        return JSONUtils.toJSONString(map);
    }

    //新增数据
    @RequestMapping(value = "page/link/add")
    @ResponseBody
    public String add(HttpServletRequest request) {
        Map map = new HashMap<Object, Object>();
        String fileName = "";
        File targetPath = new File(uploadPath + PubConstant.LINK_DIR);
        if (!targetPath.exists()) {
            targetPath.mkdirs();
        }
        //将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        //检查form中是否有enctype="multipart/form-data"
        if (multipartResolver.isMultipart(request)) {
            //将request变成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            //获取multiRequest 中所有的文件名
            Iterator iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                //一次遍历所有文件
                MultipartFile file = multiRequest.getFile(iter.next().toString());
                if (file != null) {
                    fileName = file.getOriginalFilename();
                    String suffixName = fileName.substring(fileName.lastIndexOf("."));
                    //重新生成文件名
                    fileName = CommUtil.getUUIDUpperCase() + suffixName;
                    String path = uploadPath + PubConstant.LINK_DIR + fileName;
                    //上传
                    try {
                        file.transferTo(new File(path));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        String webname = request.getParameter("webname");
        String webmaster = request.getParameter("webmaster");
        String phone = request.getParameter("phone");
        String email = request.getParameter("email");
        String url = request.getParameter("url");
        Link link = new Link();
        link.setWebname(webname);
        link.setUrl(url);
        link.setWebmaster(webmaster);
        link.setPhone(phone);
        link.setEmail(email);
        link.setWebicon(fileName);
        link.setStatus(PubConstant.STS_1);
        linkService.add(link);

        map.put(PubConstant.flag, PubConstant.success);

        return JSONUtils.toJSONString(map);
    }


    //删除数据
    @RequestMapping(value = "page/link/delete", method = RequestMethod.POST)
    @ResponseBody
    public String delete(@Param(value = "id") int id, HttpServletRequest request) {
        Map map = new HashMap();
        //判断权限
        User userinfo = (User) request.getSession().getAttribute(PubConstant.GLOBAL_SESSION_NAME);
        if (userinfo == null || !PubConstant.YES_NO_Y.equals(userinfo.getAdminflag())) {
            //普通用户或者游客 无权限删除文章
            map.put(PubConstant.flag, PubConstant.permissions);
        } else {
            //管理人员 无限制
            try {
                //删除文件
                Link link = linkService.find(id);
                String fileName = link.getWebicon();
                File file = new File(uploadPath + PubConstant.LINK_DIR + fileName);
                if (file.exists()) {
                    file.delete();
                }
            } catch (Exception e) {

            }
            linkService.delete(id);
            map.put(PubConstant.flag, PubConstant.success);
        }
        return JSONUtils.toJSONString(map);
    }

    //删除数据
    @RequestMapping(value = "page/link/status", method = RequestMethod.POST)
    @ResponseBody
    public String delete(HttpServletRequest request, int id, int status) {
        Map map = new HashMap();
        //判断权限
        User userinfo = (User) request.getSession().getAttribute(PubConstant.GLOBAL_SESSION_NAME);
        if (userinfo == null || !PubConstant.YES_NO_Y.equals(userinfo.getAdminflag())) {
            //普通用户或者游客 无权限删除文章
            map.put(PubConstant.flag, PubConstant.permissions);
        } else {
            //管理人员 无限制

            linkService.updateSts(id, status);
            map.put(PubConstant.flag, PubConstant.success);
        }
        return JSONUtils.toJSONString(map);
    }

}
